<template>
    <div class="layout-route">
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                <el-form-item label="订单编号" prop="order_number">
                    <el-input type="textarea" :rows="4" v-model="queryParams.order_number" placeholder="请输入订单编号" clearable size="small" style="width: 240px" />
                </el-form-item>
                <el-form-item label="订单号" prop="order_id">
                    <el-input type="textarea" :rows="4" v-model="queryParams.order_id" placeholder="请输入订单号" clearable size="small" style="width: 240px" />
                </el-form-item>
                <el-form-item label="店铺" prop="shop_id">
                    <el-select v-model="queryParams.shop_id" placeholder="请选择店铺" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.shopList" :key="index" :label="dict.shop_name" :value="dict.shop_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部分退款" prop="is_part">
                    <el-select v-model="queryParams.is_part" placeholder="全部" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.isPartStatus" :key="index" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="操作人" prop="operater_id">
                    <SelectPage
                        v-model="queryParams.operater_id"
                        placeholder="请选择操作人员"
                        :url="$api.purchase.getPurchaserList"
                        show_field="username"
                        show_id="operater_id"
                        query_field="keyword"
                        filterable
                        clearable
                        popper-class="custom-select"
                        style="width: 240px"
                    ></SelectPage>
                </el-form-item>

                <!-- <el-form-item label="操作人" prop="operate_id">
                    <el-select v-model="queryParams.operate_id" placeholder="请选择操作人" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.salesmanList" :key="index" :label="dict.username" :value="dict.operater_id" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="创建时间" prop="create_time">
                        <el-date-picker v-model="queryParams.create_time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px">
                        </el-date-picker>
                    </el-form-item>
                    
                <el-form-item label="退款意向" prop="SpecificReasons">
                    <el-select v-model="queryParams.SpecificReasons" placeholder="全部" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.SpecificReasons" :key="index" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5" v-hasPermi="api.BatchCreateRefunds">
                    <el-button type="primary" @click="createRegister">批量创建退款</el-button>
                </el-col>
                <el-col :span="1.5" v-hasPermi="api.Batchaction">
                    <upload-button :action="action"></upload-button>
                </el-col>
                <el-col :span="1.5" v-hasPermi="api.BatchList">
                    <el-button @click="showRegisterDialog">批次列表</el-button>
                </el-col>
                <el-col :span="1.5" v-hasPermi="api.BatchExport">
                    <el-button type="warning" plain icon="el-icon-download" :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <el-col :span="1.5" v-hasPermi="api.BatchdownloadExcel">
                    <el-button type="warning" plain @click="downloadExcel">下载导入模板</el-button>
                </el-col>
                <el-col :span="1.5" v-hasPermi="api.ManuallyAddRefund">
                    <el-button type="warning" @click="showDetailDialog({}, 'add')" >手动新增退款</el-button>
                </el-col>
                <!-- <el-col :span="1.5">
                    <el-button type="danger" plain icon="el-icon-plus" @click="mrkAsProcessed">标记成已完成</el-button>
                </el-col> -->
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-tabs v-model="queryParams.refund_status" type="border-card" @tab-click="handleQuery">
                <el-tab-pane v-for="item in dict.refundStatus" :key="item.value" :label="item.label" :name="item.value"></el-tab-pane>
            </el-tabs>
            <div class="table-wrap">
                <el-table v-loading="loading" :data="tableData" border script @selection-change="handleSelectionChange" ref="multipleTable">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="店铺" prop="shop_name" min-width="100" show-overflow-tooltip></el-table-column>
                    <el-table-column label="订单编号" prop="order_number" min-width="80" show-overflow-tooltip></el-table-column>
                    <el-table-column label="订单号" prop="order_id" min-width="140" show-overflow-tooltip></el-table-column>
                    <el-table-column label="支付渠道" prop="payment_gateway_names" min-width="140" show-overflow-tooltip></el-table-column>
                    <el-table-column label="部分退款" prop="is_part" min-width="80">
                        <template slot-scope="scope">
                            {{ scope.row.is_part | formatLabelByValueFuzzy(dict.isPartStatus) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="退款金额" prop="refund_payment" min-width="80" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.refund_payment" @change="editRefundPayment(scope.row)" v-if="queryParams.refund_status == 0"></el-input>
                            <span v-else>{{ scope.row.refund_payment }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="货币类型" prop="currency" min-width="80"></el-table-column>
                    <el-table-column label="支付金额" prop="payment" min-width="80"></el-table-column>
                    <el-table-column v-if="queryParams.refund_status == 2 || queryParams.refund_status == 'all'" label="退款比例" prop="refund_rate" min-width="80" show-overflow-tooltip></el-table-column>
                    <el-table-column label="发货状态" prop="fulfillment_status" min-width="80"></el-table-column>
                    <el-table-column label="会话数量" prop="conversations">
                        <template slot-scope="scope">
                            <el-link type="primary" @click="showConversaDialog(scope.row)">{{ scope.row.conversations }}</el-link>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作人" prop="operater" min-width="80"></el-table-column>
                    <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
                    <el-table-column label="支付时间" prop="createtime" min-width="160"></el-table-column>
                    <el-table-column label="退款原因" prop="ReasonForRefund" min-width="160"></el-table-column>
                    <el-table-column label="补充描述" prop="Supplementary" min-width="160"></el-table-column>
                    <el-table-column label="退款意向" prop="SpecificReasons" min-width="160"></el-table-column>
                    <el-table-column label="退款结果" prop="refund_status_msg" min-width="160"></el-table-column>
                    <el-table-column label="SKU" prop="skus" min-width="160"></el-table-column>
                    <el-table-column label="操作" min-width="120">
                        <template slot-scope="scope">
                            <el-button type="text" @click="showDetailDialog(scope.row, 'edit')" v-if="scope.row.refund_status !== 20">编辑</el-button>
                            <el-button type="text" @click="showLog(scope.row)" v-if="scope.row.refund_status == 2 || scope.row.refund_status == 3">查看日志</el-button>
                            <el-button type="text" @click="Removelog(scope.row)" v-if="scope.row.refund_status == 0">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList"></pagination>
        </div>

        

        <el-drawer title="批次列表" :visible.sync="registerDialog.visible" direction="rtl" append-to-body size="60%">
            <el-table v-loading="batchLoading" :data="batchList" border script>
                <el-table-column label="批次ID" prop="id" min-width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="数量" prop="num" min-width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
                <el-table-column label="更新时间" prop="update_time" min-width="160"></el-table-column>
                <!-- <el-table-column label="" prop="refund_payment" min-width="120" show-overflow-tooltip>
                    <template #header>
                        <div>退款金额</div>
                        <div>（<span style="color: #11a983; cursor: pointer" @click="refundDialogVisible = true">批量</span>）</div>
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.refund_payment" @change="editRefundPayment(scope.row)"></el-input>
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width="160" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="showBatchDetailDialog(scope.row)">查看详情</el-button>
                        <el-button type="text" icon="el-icon-download" @click="exportBatchDetail(scope.row)">导出</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog title="退款金额" :visible="refundDialogVisible" append-to-body width="420px">
                <el-form :model="formData" label-width="100px">
                    <el-form-item label="退款金额">
                        <el-input v-model="formData.refundAmount" placeholder="请输入退款金额"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submit">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </el-dialog>

            <el-dialog title="退款批量详情" :visible.sync="batchDetailDialog.visible" width="1100px" append-to-body>
                <el-table v-loading="refundLoading" :data="refundData" border script>
                    <el-table-column label="店铺" prop="shop_name" min-width="100" show-overflow-tooltip></el-table-column>
                    <el-table-column label="订单编号" prop="order_number" min-width="80" show-overflow-tooltip></el-table-column>
                    <el-table-column label="订单号" prop="order_id" min-width="140" show-overflow-tooltip></el-table-column>
                    <el-table-column label="退款状态" prop="status" min-width="100">
                        <template slot-scope="scope">
                            {{ scope.row.status | formatLabelByValueFuzzy(dict.refundStatus) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="退款金额" prop="refund_payment" min-width="80" show-overflow-tooltip></el-table-column>
                    <el-table-column label="货币类型" prop="currency" min-width="80"></el-table-column>
                    <el-table-column label="退款ID" prop="refund_id" min-width="120"></el-table-column>
                    <el-table-column label="退款结果" prop="msg" min-width="100">
                        <template slot-scope="scope">
                            {{ scope.row.msg }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作人" prop="operater" min-width="120"></el-table-column>
                    <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
                </el-table>
                <pagination v-show="refundTotal > 0" :total="refundTotal" :page.sync="refundPage.page" :limit.sync="refundPage.limit" @pagination="getList"></pagination>
            </el-dialog>
        </el-drawer>
        <el-dialog title="退货订单日志" :visible.sync="logDialog.visible" width="1100px" append-to-body>
            <el-table v-loading="logLoading" :data="logData" border script>
                <el-table-column label="店铺" prop="shop_name" min-width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="订单编号" prop="order_number" min-width="80" show-overflow-tooltip></el-table-column>
                <el-table-column label="订单号" prop="order_id" min-width="140" show-overflow-tooltip></el-table-column>
                <el-table-column label="退款状态" prop="status" min-width="100">
                    <template slot-scope="scope">
                        {{ scope.row.status | formatLabelByValueFuzzy(dict.refundStatus) }}
                    </template>
                </el-table-column>
                <el-table-column label="退款金额" prop="refund_payment" min-width="80" show-overflow-tooltip></el-table-column>
                <el-table-column label="货币类型" prop="currency" min-width="80"></el-table-column>
                <el-table-column label="退款结果" prop="msg" min-width="100">
                    <template slot-scope="scope">
                        {{ scope.row.msg }}
                    </template>
                </el-table-column>
                <el-table-column label="操作人" prop="operater" min-width="120"></el-table-column>
                <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
            </el-table>
            <pagination v-show="logDialog.total > 0" :total="logDialog.total" :page.sync="logDialog.pageInfo.page" :limit.sync="logDialog.pageInfo.limit" @pagination="refundListLog" />
        </el-dialog>

        <DetailDialog v-model="detailDialog.visible" v-if="detailDialog.visible" :params="detailDialog.data" :type="detailDialog.type" @success="handleQuery"></DetailDialog>

        <ConversaDialog v-model="conversaDialog.visible" v-if="conversaDialog.visible" :params="conversaDialog.data" :type="conversaDialog.type" @success="handleQuery"></ConversaDialog>
        
    </div>
</template>

<script>
import { getList, batchRefund, getBatchList, refundEdit, getBatchDetailList, exportrefundList, exportBatchDetailList, refundListLog,RefundDel } from '@/api/orderRegister'
import { getShopList, getSalesmanList } from '@/api/shop'
import { getPurchaserList } from '@/api/purchase'
import ConversaDialog from './components/ConversaDialog.vue'
import DetailDialog from './components/DetailDialog.vue'
import { exportFile } from '@/utils/index'
import { parseTime } from '@/utils/quickadmin'
export default {
    name: 'OrderRegisterList',
    components: { DetailDialog ,ConversaDialog},
    data() {
        return {
            api: {
                BatchCreateRefunds: `dispute/register/BatchCreateRefunds`,
                Batchaction: `dispute/register/Batchaction`,
                BatchList: `dispute/register/BatchList`,
                BatchExport: `dispute/register/BatchExport`,
                BatchdownloadExcel: `dispute/register/BatchdownloadExcel`,
                ManuallyAddRefund: `dispute/register/ManuallyAddRefund`,
            },
            action: process.env.VUE_APP_BASE_API + '/customer/OrderRefund/importInfo',
            downloadUrl: process.env.VUE_APP_BASE_API + '/storage/system/refund_order.xls',
            // 遮罩层
            loading: true,
            batchLoading: false,
            refundLoading: false,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 表格数据
            tableData: [],
            batchList: [],
            refundData: [],
            refundTotal: 0,
            refundPage: {
                page: 1,
                limit: 10,
            },
            conversaDialog: {
                visible: false,
                data: {},
                type: ''
            },
            dict: {
                //  1:退款中 2:退款成功 3:退款失败 4:已处理
                refundStatus: [
                    { label: '全部', value: 'all' },
                    { label: '待退款', value: '0' },
                    { label: '退款中', value: '1' },
                    { label: '退款成功', value: '2' },
                    { label: '退款失败', value: '3' },
                    { label: '已处理', value: '4' },
                ],
                // 是否部分退款 0:否 1:是
                isPartStatus: [
                    { label: '否', value: 0 },
                    { label: '是', value: 1 },
                ],
                SpecificReasons: [{
                        value: '有退款意向',
                        label: '有退款意向'
                    },{
                        value: '确认退款',
                        label: '确认退款'
                    },{
                        value: '产品问题反馈',
                        label: '产品问题反馈'
                    },{
                        value: '补发',
                        label: '补发'
                    },
                ],
                shopList: [],
                salesmanList: [],
            },

            // 查询参数
            queryParams: {
                shop_id: undefined,
                order_number: undefined,
                order_id: undefined,
                operate_id: undefined,
                is_part: undefined,
                refund_status: 'all',
                create_time: [],
            },
            detailDialog: {
                visible: false,
                data: {},
            },
            registerDialog: {
                visible: false,
                data: {},
            },
            refundDialogVisible: false,
            formData: {
                refundAmount: null,
            },
            multipleSelection: [],
            batchDetailDialog: {
                visible: false,
                data: {},
            },
            logLoading: false,
            logData: [],
            logDialog: {
                visible: false,
                data: {},
                total: 0,
                pageInfo: {
                    page: 1,
                    limit: 10,
                },
            },
        }
    },
    async created() {
        this.loading = true
        try {
            const [shopData] = await Promise.all([getShopList()])
            this.dict.shopList = shopData?.data?.list ?? []
        } catch (error) {
            this.loading = false
            console.log(error)
        }
        this.getList()
    },
    methods: {
        showLog(row) {
            this.logDialog.visible = true
            this.logDialog.pageInfo.page = 1
            this.refundListLog(row)
        },
        showDetailDialog(row, type) {
            this.detailDialog.visible = true
            this.detailDialog.data = row
            this.detailDialog.type = type
        },
        refundListLog(row) {
            this.logLoading = true
            const params = { order_id: row.order_id, ...this.logDialog.page }
            refundListLog(params)
                .then(res => {
                    this.logData = res?.data?.list ?? []
                    this.logDialog.total = res?.data?.total ?? 0
                })
                .finally(() => {
                    this.logLoading = false
                })
        },
        showRegisterDialog() {
            this.registerDialog.visible = true
            this.getBatchList()
        },
        showBatchDetailDialog(row) {
            this.batchDetailDialog.visible = true
            this.getBatchDetailList(row)
        },
        getBatchDetailList(row) {
            this.refundLoading = true
            const params = { batch_id: row.id, ...this.refundPage }
            getBatchDetailList(params).then(res => {
                this.refundData = res?.data?.list ?? []
                this.refundTotal = res?.data?.total ?? 0
                this.refundLoading = false
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val.map(item => item.id)
            console.log('test', this.multipleSelection)
        },
        createRegister() {
            if (this.multipleSelection == '') {
                return this.msgError('请勾选再操作')
            }
            this.$confirm(`是否确认批量退款?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.loading = true
                    batchRefund({ ids: this.multipleSelection })
                        .then(res => {
                            this.getList()
                            this.msgSuccess('操作成功')
                            this.multipleSelection = []
                        })
                        .finally(() => {
                            this.loading = false
                        })
                })
                .catch(() => {})
        },
        downloadExcel() {
            window.open(this.downloadUrl, '_blank')
        },

        exportBatchDetail(row) {
            exportBatchDetailList({ batch_id: row.id }).then(res => {
                exportFile(res)
            })
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            if(qyparams.refund_status == 'all' ) {
                qyparams.refund_status = ''
            }

            exportrefundList(qyparams)
                .then(res => {
                    console.log(res)
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        showConversaDialog(row, type) {
            this.conversaDialog.visible = true
            this.conversaDialog.data = row
        },
        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            if(qyparams.refund_status == 'all' ) {
                qyparams.refund_status = ''
            }
            getList(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.total = response.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },

        Removelog(item){
            this.$confirm(`是否确认删除?`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true
                RefundDel(item)
                    .then(res => {
                        this.$message.success(res.msg)
                        this.resetQuery()
                    })
                    .finally(() => {
                        this.loading = false
                    })
            }).catch(() => { })
        },

        getBatchList() {
            this.batchLoading = true
            const qyparams = {
                // ...this.pageInfo,
                // ...this.queryParams,
            }
            getBatchList(qyparams)
                .then(response => {
                    this.batchList = response.data.list
                    this.batchTotal = response.data.total
                })
                .finally(() => {
                    this.batchLoading = false
                })
        },
        advaccountAbnormalConfirm(row) {
            this.$confirm('是否确认移除', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                // advaccountAbnormalConfirm({ id: row.id }).then(() => {
                //     this.$message.success('操作成功')
                //     this.handleQuery()
                // })
            })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },
        // 单个修改金额
        editRefundPayment(row) {
            const params = {
                id: row.id,
                refund_payment: row.refund_payment,
            }
            refundEdit(params).then(() => {
                this.msgSuccess('操作成功')
                this.getList()
            })
        },
        submit() {
            if (!this.formData.refundAmount) {
                return this.$message.error('请输入退款金额')
            }
            // this.$refs.form.validate(valid => {
            refundEdit(this.formData).then(() => {
                this.msgSuccess('操作成功')
                this.getBatchList()
                this.cancel()
            })
            // })
        },
        cancel() {
            this.refundDialogVisible = false
        },
    },
}
</script>
<style scoped>
::v-deep .el-tabs .el-tabs__content {
    padding: 0;
    border-bottom: 0;
}
.el-tabs--border-card {
    box-shadow: none;
    border-bottom: 0;
}

::v-deep .el-tabs .el-tabs__content {
    padding: 0;
    border-bottom: 0;
}
.table-wrap {
    padding: 15px;
    border-bottom: 1px solid #dfe4ed;
    border-left: 1px solid #dfe4ed;
    border-right: 1px solid #dfe4ed;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}
</style>
